import 'dart:async';
import 'package:flutter/material.dart';

/// 自定义指示器的核心要点
///
/// 1.设置pageview
/// 2.定时器
/// 3.设置_pageController.animateToPage

class Swiper extends StatefulWidget {
  final List<String> bgUrls;
  final double height;
  final double width;
  const Swiper(
      {super.key,
      this.height = 200,
      this.width = double.infinity,
      required this.bgUrls});

  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  final PageController _pageController = PageController(initialPage: 0);
  int _currentIndex = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Timer.periodic(const Duration(seconds: 3), (time) {
      _pageController.animateToPage(
          (_currentIndex + 1) % (widget.bgUrls.length),
          duration: const Duration(milliseconds: 200),
          curve: Curves.linear);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        /// 图片展示
        PageView(
          controller: _pageController,
          onPageChanged: (index) {
            print(index);
            setState(() {
              _currentIndex = index;
            });
          },
          children: widget.bgUrls.map((str) {
            return SwiperItem(str);
          }).toList(),
        ),

        /// 指示器
        Positioned(
            left: 0,
            right: 0,
            bottom: 5,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: _indicatorCreate(),
            ))
      ],
    );
  }

  List<Widget> _indicatorCreate() {
    List<Widget> indicators = [];
    for (var i = 0; i < widget.bgUrls.length; i++) {
      indicators.add(Container(
        margin: const EdgeInsets.only(left: 5),
        width: 10,
        height: 10,
        decoration: BoxDecoration(
            color: _currentIndex == i ? Colors.red : Colors.grey,
            borderRadius: BorderRadius.circular(5)),
      ));
    }

    return indicators;
  }
}

class SwiperItem extends StatefulWidget {
  final double height;
  final double width;
  final String? bgurl;
  SwiperItem(
    this.bgurl, {
    super.key,
    this.height = 200,
    this.width = double.infinity,
  });

  @override
  State<SwiperItem> createState() => _SwiperItemState();
}

class _SwiperItemState extends State<SwiperItem> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.height,
      width: widget.width,
      child: Image.network(
        widget.bgurl!,
        fit: BoxFit.cover,
      ),
    );
  }
}
